<template>
    <div class="member-list-main">
        <ZwSearchForm
            :option="searchOption"
            @input="changeSearchForm"
            @search="search"
            @reset="reset"
            @expand="getTableH" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-data-format="fetchDataFormat"
            :param-prop="state.paramProp"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @updateData="getTableData">
            <template #headerOperate>
                <div class="gc-content">
                    <div class="left">
                        <div v-auth="'CONFIG_REMIND'" class="remind" @click="remindConfig">
                            <span>配置提醒</span>
                            <span v-show="isEnable == 1" class="open">已开启</span>
                            <span v-show="isEnable != 1" class="open">已关闭</span>
                        </div>
                    </div>
                    <div class="right">
                        <!-- <el-button type="primary" v-auth="'EXPORT'" @click="handlerExport">会员导出</el-button> -->
                    </div>
                </div>
            </template>
        </ZwTable>
        <GrowthValueDetails ref="growthValueDetailsRef" />
        <PointsDetails ref="pointsDetailsRef" />
        <!-- 配置提醒弹框 of start -->
        <Dialog ref="dialogRef" :app-dialog="appDialog" class="dialogForm">
            <div v-show="isAllot" class="inform">
                <div class="inform_icon"></div>
                <div class="inform_text">开启通知后, 选择的【成员】将会在企业微信中收到冲突提醒通知。</div>
            </div>
            <div class="formData">
                <el-form label-width="100px" :model="formData">
                    <el-form-item v-show="isAllot" label="开通通知提醒:">
                        <div class="switch">
                            <el-switch v-model="formData.switch" class="mb-2" :active-value="1" :inactive-value="0" />
                            <span v-show="formData.switch == 1" class="text">已开启</span>
                            <span v-show="formData.switch != 1" class="text">已关闭</span>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <Member ref="member" :type="1"></Member>
                    </el-form-item>
                </el-form>
            </div>
        </Dialog>
        <!-- 配置提醒弹框 of end -->
        <!-- 冲突提醒弹框 of end -->
        <ConflictDetail
            ref="ConflictDetailRef"
            :app-dialog="conflictDialog"
            :conflict-type="conflictType"
            :member_no="conflictDialog.member_no"></ConflictDetail>
        <!-- 冲突提醒弹框 of end -->
    </div>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'MEMBER_MANAGE_LIST' });
</script>

<script setup lang="tsx">
import { ref, reactive, onMounted, computed, nextTick, onActivated } from 'vue';
import { ElMessage, ElButton } from 'element-plus';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import GrowthValueDetails from './components/GrowthValueDetails.vue';
import PointsDetails from './components/PointsDetails.vue';
import TableTooltip from './components/TableTooltip.vue';
import { getDictEnum } from '@/api/ecommerce/storeManage';
import { memberConflictInfo } from '@/api/member/memberList/index';

import {
    getMemberList,
    getMemberListExport,
    getMemberChannelList,
    memberClashHandle,
    reminDetail,
    memberConfilictRemin
} from '@/api/member/memberList/index';
import { getMemberLevelList } from '@/api/member/memberLevel/index';
import { getWiseManList } from '@/api/ecommerce/wiseManList';
import { deepCopy } from '@/utils/helper';
import { downloadFile } from '@/utils/utils';
import { useRouter } from 'vue-router';

import { getSetionId } from '@/utils/utils';
import Dialog from '@/components/Dialog.vue';
import Member from './components/Member.vue';
import ConflictDetail from './ConflictDetail.vue';

const router = useRouter();

const tableRef = ref<any>(null);
const growthValueDetailsRef = ref<any>(null);
const pointsDetailsRef = ref<any>(null);
const currentParams = ref<any>(null);

/* ------------------------ 冲突提醒弹框 of start -------------------- */

// 冲突类型：1-无冲突 2-初始化冲突 3-换绑冲突
const conflictType = ref(1);

const ConflictDetailRef = ref(null);

/**
 * 冲突提醒弹框取消事件
 */
const cancelHandelConfilict = () => {
    conflictDialog.visible = false; // 关闭弹框
    conflictType.value = 1; // 冲突类型置为默认值
    conflictDialog.shop_id = ''; // 店铺id置为空
    conflictDialog.member_no = ''; // 会员id置为空
};

/**
 * 冲突提醒弹框取确认事件
 */

const submitHandelConfilict = () => {
    const params = {
        member_no: conflictDialog.member_no, //会员id
        conflict_scene: ConflictDetailRef.value.conflictScene //1-换绑 2-整体换绑
    };
    memberClashHandle(params).then((res: any) => {
        if (res) ElMessage.success('操作成功');
        conflictDialog.visible = false; // 关闭弹框
        tableRef.value.reload();
    });
};

/**
 * 冲突提醒弹框
 */
const conflictDialog = reactive({
    visible: false,
    title: '查看冲突',
    width: '800px',
    cancel: cancelHandelConfilict,
    submit: submitHandelConfilict,
    cancelText: '取消',
    submitText: '确定',
    shop_id: '', // 店铺id
    member_no: '' // 会员ID
});

/**
 * @description 查看冲突详情
 * @param val
 */
const handlerConflictDetail = (val: any) => {
    conflictType.value = val.conflict_type;
    conflictDialog.shop_id = val.id;
    conflictDialog.member_no = val.member_no;
    ConflictDetailRef.value.conflictScene = 1;
    const params = {
        member_no: val.member_no, // 会员ID
        conflict_scene: 1 // 解决冲突时的场景
    };
    memberConflictInfo(params).then((res: any) => {
        if (res) {
            conflictDialog.visible = true;
        }
    });
};

/* ------------------------ 冲突提醒弹框 of end -------------------- */

/* ------------------------ 配置提醒弹框 of start -------------------- */
const member = ref(null); //选择员工组建实例
const isAllot = ref(true); //是否开启通知
const isEnable = ref(0); //配置提醒0已关闭1已开启
const formData = ref({
    switch: 0, // 是否开启提醒 1--> 开 2-->关
    work_user_ids: [], //员工列表IDS
    work_users: [] // 员工列表
}); // 配置提醒弹框表单数据

/**
 * 配置提醒弹框取消事件
 */
const cancelHandel = () => {
    appDialog.visible = false;
};

/**
 * 配置提醒弹框确认事件
 */
const submitHandel = async () => {
    formData.value.work_user_ids = getSetionId('id', member.value?.selectedMember);
    const res = await memberConfilictRemin({
        switch: formData.value.switch,
        work_user_ids: formData.value.work_user_ids
    });
    if (res) ElMessage.success('操作成功');
    await getreminDetail();
    appDialog.visible = false;
};

/**
 * 配置提醒弹框数据
 */
const appDialog = reactive({
    visible: false,
    title: '通知提醒设置',
    width: '800px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
});

/**
 * 获取冲突提醒详情
 */
const getreminDetail = () => {
    return new Promise<void>((resolve, reject) => {
        reminDetail()
            .then((res: any) => {
                Object.assign(formData.value, res);
                isEnable.value = res.switch;
                resolve(res);
            })
            .catch((err: any) => {
                reject(err);
            });
    });
};

/**
 * 获取冲突提醒详情数据之后打开配置提醒弹框
 */
const remindConfig = () => {
    getreminDetail().then((res: any) => {
        appDialog.visible = true;
        appDialog.title = '通知提醒设置';
        nextTick(() => {
            member.value.selectedMember = res ? res.work_users : [];
        });
    });
};

/* ------------------------ 配置提醒弹框 of end -------------------- */

const searchOption = computed(() => {
    return [
        {
            label: '会员信息',
            name: 'keywords',
            type: 'input',
            clearable: true,
            placeholder: '请输入会员ID/昵称/手机号'
        },
        {
            label: '会员等级',
            name: 'level_id',
            type: 'select',
            value: '',
            clearable: true,
            placeholder: '请选择会员等级',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getMemberLevelList({ switch: 1 }).then((res: any) => {
                        let list: any = [];
                        list = res.data || [];
                        resolve(list);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.member_level_name,
                value: v.id
            })
        },
        {
            label: '入会时间',
            name: 'shop_join_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '可用积分',
            name: 'available_points',
            value: [],
            type: 'section',
            isForbidNegativeNumber: true,
            maxNum: '99999999',
            placeholder: '请输入可用积分'
        },
        {
            label: '来源渠道',
            name: 'join_channel',
            type: 'select',
            value: [],
            clearable: true,
            placeholder: '请选择来源渠道',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    const params = { dict_id: 1 };
                    getMemberChannelList({ type: 3 }).then((res: any) => {
                        const targetArr: any = [];
                        res.forEach((item: any) => {
                            targetArr.push(item);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '来源店铺',
            name: 'join_shop_id',
            value: [],
            type: 'select',
            placeholder: '全部',
            popperClass: 'zw-hide_select_option',
            isStoreSelect: true,
            isStoreDisabledSelect: false,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '下单渠道',
            name: 'order_channel',
            type: 'select',
            value: [],
            clearable: true,
            placeholder: '请选择下单渠道',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    const params = { dict_id: 1 };
                    getMemberChannelList({ type: 2 }).then((res: any) => {
                        const targetArr: any = [];
                        res.forEach((item: any) => {
                            targetArr.push(item);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '下单店铺',
            name: 'order_shop_id',
            value: [],
            type: 'select',
            placeholder: '全部',
            popperClass: 'zw-hide_select_option',
            isStoreSelect: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '下单达人',
            name: 'daren_openid',
            value: '',
            type: 'select',
            placeholder: '全部',
            clearable: true,
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getWiseManList({ auth_status: [2, 3], page: 1, page_size: 999 }).then((res: any) => {
                        const targetArr: any = [];
                        res?.data?.forEach((item: any) => {
                            targetArr.push(item);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.daren_name,
                value: v.daren_openid
            })
        },
        {
            label: '实付金额',
            name: 'total_order_amount',
            value: [],
            type: 'section',
            isForbidNegativeNumber: true,
            maxNum: '99999999.99'
        },
        {
            label: '累计支付单数',
            name: 'total_order_num',
            value: [],
            type: 'section',
            isForbidNegativeNumber: true,
            maxNum: '99999999'
        },
        {
            label: '客单价',
            name: 'avg_order_amount',
            value: [],
            type: 'section',
            isForbidNegativeNumber: true,
            maxNum: '99999999.99'
        },
        {
            label: '购买频次',
            name: 'avg_order_rate',
            value: [],
            type: 'section',
            isForbidNegativeNumber: true,
            maxNum: '99999999'
        },
        {
            label: '上次购买距今/天',
            name: 'last_order_interval',
            value: [],
            type: 'section',
            isForbidNegativeNumber: true,
            maxNum: '3650'
        },
        {
            label: '生日',
            name: 'birthday',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '是否关联客户',
            name: 'relation_cust',
            value: '',
            type: 'select',
            placeholder: '请选择',
            optionList: [
                {
                    label: '是',
                    value: 1
                },
                {
                    label: '否',
                    value: 2
                }
            ]
        },
        {
            label: '冲突',
            name: 'conflict_type',
            value: '',
            type: 'select',
            placeholder: '请选择',
            optionList: [
                {
                    label: '不冲突',
                    value: 1
                },
                {
                    label: '初始化冲突',
                    value: 2
                },
                {
                    label: '换绑冲突',
                    value: 3
                }
            ]
        }
    ];
});

const tableOption = [
    {
        prop: 'member_no',
        label: '会员ID',
        width: 190,
        render({ row, column, index }: any) {
            return (
                <div class="pointer-name" onClick={() => handlerDetail(row)}>
                    {row.member_no || '--'}
                </div>
            );
        }
    },
    {
        prop: 'mobile',
        label: '手机号',
        width: 140,
        render({ row, column, index }: any) {
            return <div>{row.mobile || '--'}</div>;
        }
    },
    {
        prop: 'nickname',
        label: '会员昵称',
        width: 150,
        render({ row, column, index }: any) {
            return <div>{row.nickname || '--'}</div>;
        }
    },
    {
        prop: 'level_name',
        label: '会员等级',
        width: 160,
        render({ row, column, index }: any) {
            return <div>{row.level_name || '--'}</div>;
        }
    },
    {
        prop: 'points.available_points',
        label: '可用积分',
        width: 100,
        render({ row, column, index }: any) {
            return (
                <div class="pointer-name" onClick={() => handlerPointsVal(row)}>
                    {row.points?.available_points || '--'}
                </div>
            );
        }
    },
    {
        prop: 'join_channel_name',
        label: '来源渠道',
        minWidth: 150,
        render({ row, column, index }: any) {
            return <div>{row.join_channel_name || '--'}</div>;
        }
    },
    {
        prop: 'join_shop_name',
        label: '来源店铺',
        minWidth: 150,
        render({ row, column, index }: any) {
            return <div>{row.join_shop_name || '--'}</div>;
        }
    },
    {
        prop: 'order_channel',
        label: '下单渠道',
        width: 150,
        render({ row, column, index }: any) {
            return <elPopoverTips content={row.order_channel} isArr={true} />;
        }
    },
    {
        prop: 'order_shop',
        label: '下单店铺',
        minWidth: 150,
        render({ row, column, index }: any) {
            return <elPopoverTips content={row.order_shop} isArr={true} />;
        }
    },
    {
        prop: 'order_daren',
        label: '下单达人',
        minWidth: 150,
        render({ row, column, index }: any) {
            // return <elPopoverTips content={row.order_shop} isArr={true} />;
            const { order_daren: order_daren = [] } = row;
            if (!order_daren || !order_daren.length) {
                return '--';
            } else {
                return <TableTooltip content={order_daren} />;
            }
        }
    },
    {
        prop: 'total_order_amount',
        label: '实付金额',
        width: 100,
        render({ row, column, index }: any) {
            return <div>{row.total_order_amount || '--'}</div>;
        }
    },
    {
        prop: 'total_order_num',
        label: '累计支付单数',
        width: 120,
        render({ row, column, index }: any) {
            return <div>{row.total_order_num || '--'}</div>;
        }
    },
    {
        prop: 'avg_order_amount',
        label: '客单价',
        width: 100,
        render({ row, column, index }: any) {
            return <div>{row.avg_order_amount || '--'}</div>;
        }
    },
    {
        prop: 'avg_order_rate',
        label: '购买频次/天',
        width: 120,
        render({ row, column, index }: any) {
            return <div>{row.avg_order_rate || '--'}</div>;
        }
    },
    {
        prop: 'last_order_interval',
        label: '上次购买距今/天',
        width: 150,
        render({ row, column, index }: any) {
            return <div>{row.last_order_interval || '--'}</div>;
        }
    },
    {
        prop: 'birthday',
        label: '生日',
        width: 100,
        render({ row, column, index }: any) {
            return <div>{row.birthday || '--'}</div>;
        }
    },
    {
        prop: 'relation_cust',
        label: '是否关联客户',
        width: 120,
        render({ row, column, index }: any) {
            return <div>{row.relation_cust == 1 ? '是' : '否' || '--'}</div>;
        }
    },
    {
        prop: 'conflict_type_name',
        label: '冲突',
        render({ row, column, index }: any) {
            return <div>{row.conflict_type_name || '--'}</div>;
        }
    },
    /**
     * 有赞会员通需求，加入时间改为入会时间
     */
    {
        prop: 'shop_join_time',
        label: '入会时间',
        width: 100,
        render({ row, column, index }: any) {
            return <div>{row.shop_join_time || '--'}</div>;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 140,
        isOperate: true,
        render({ row, column, index }: any) {
            return (
                <div class="zw-table__btn-box">
                    <ElButton size="small" disabled={!row.member_no} vAuth={'VIEW'} onClick={() => handlerDetail(row)}>
                        查看详情
                    </ElButton>
                    <ElButton
                        size="small"
                        vShow={row.conflict_type !== 1}
                        vAuth={'LOOK_CONFLIFLICT'}
                        onClick={() => handlerConflictDetail(row)}>
                        查看冲突
                    </ElButton>
                </div>
            );
        }
    }
];

const defaultParams = {
    keywords: '',
    level_id: '',
    shop_join_time: [],
    available_points: [],
    join_channel: [],
    join_shop_id: [],
    order_channel: [],
    daren_openid: '',
    order_shop_id: [],
    total_order_amount: [],
    total_order_num: [],
    avg_order_amount: [],
    avg_order_rate: [],
    last_order_interval: [],
    birthday: [],
    relation_cust: '',
    conflict_type: '' // 是否冲突
};

const state = reactive({
    searchParams: deepCopy(defaultParams),
    inputParams: deepCopy(defaultParams),
    paramProp: { page: 'page', pageSize: 'page_size' }
});

const getRowKey = (row: any) => {
    return row.id;
};

const changeSearchForm = (data: any): void => {
    state.inputParams = data;
};

const search = (data: any) => {
    if (data.join_channel) {
        data.join_channel = [data.join_channel];
    }
    if (data.join_shop_id) {
        data.join_shop_id = [data.join_shop_id];
    }
    if (data.order_channel) {
        data.order_channel = [data.order_channel];
    }
    if (data.daren_openid) {
        data.daren_openid = [data.daren_openid];
    }
    if (data.order_shop_id) {
        data.order_shop_id = [data.order_shop_id];
    }
    currentParams.value = deepCopy({ ...defaultParams, ...data });
    state.searchParams = deepCopy({ ...defaultParams, ...data });
};

const reset = () => {
    state.searchParams = deepCopy({ ...defaultParams });
    state.inputParams = deepCopy({ ...defaultParams });
    currentParams.value = deepCopy({ ...defaultParams });
};

const fetchDataFormat = (list: any) => {
    return list.filter((el: any) => el);
};

const fetchApi = () => {
    getTableH();
    return getMemberList;
};
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
onMounted(() => {
    getTableH();
    getreminDetail();
});
const getTableData = (val?: any) => {};

const handlerDetail = (val: any) => {
    if (!val.member_no) {
        return;
    }
    router.push(`/member/memberManage/memberList/detail?member_no=${val.member_no}`);
};

const handlerExport = async () => {
    const { url: url = '' } = await getMemberListExport(state.inputParams);
    url && downloadFile(url);
};

const handlerGrowthVal = (val?: any) => {
    growthValueDetailsRef.value.state.searchParams.member_no = '';
    growthValueDetailsRef.value.state.searchParams.member_no = val.member_no;
    growthValueDetailsRef.value.appDialog.visible = true;
};

const handlerPointsVal = (val?: any) => {
    pointsDetailsRef.value.state.searchParams.member_no = '';
    pointsDetailsRef.value.state.searchParams.member_no = val.member_no;
    // pointsDetailsRef.value.appDialog.visible = true;
    // 跳转会员详情积分明细
    router.push(`/member/memberManage/memberList/detail?member_no=${val.member_no}&tab=${3}`);
};

onActivated(() => {
    state.searchParams = deepCopy({ ...defaultParams, ...currentParams.value });
});
</script>
<style lang="scss" scoped>
.member-list-main {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }

    :deep(.pointer-name) {
        cursor: pointer;
        color: #ff6b00;
    }
}

.gc-content {
    width: calc(100vw - 365px);
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
        display: flex;
        align-items: center;

        .remind {
            font-size: 13px;
            color: #33302d;
            padding: 10px 12px;
            box-sizing: border-box;
            background: #f9f9f9;
            border-radius: 1px;
            border: 1px solid #eaeaea;
            cursor: pointer;

            .open {
                padding-left: 8px;
                color: #3e82f9;
            }
        }
    }

    .right {
        display: flex;
        align-items: center;
    }
}
</style>
